<template>
  <!-- up-popup 组件，用于显示底部弹出框 -->
  <up-popup
    :show="show"
    mode="bottom"
    closeable
    round="10"
    @close="show = false"
  >
    <!-- 弹出框内容区域 -->
    <view class="content p-20">
      <!-- 标题 -->
      <u-text size="18" bold align="center" :text="title"></u-text>
      <!-- 间隔 -->
      <u-gap height="10"></u-gap>
      <!-- 商品预览区域 -->
      <view class="preview flex">
        <!-- 商品图片 -->
        <view style="width: 240rpx; height: 240rpx">
          <u-image
            :src="currentSku.image_url"
            width="240rpx"
            height="240rpx"
            radius="10"
            @click="handlePreviewImage"
          ></u-image>
        </view>
        <!-- 商品信息 -->
        <view class="info ml-20 flex flex-column justify-around">
          <!-- 商品价格、条码和库存信息 -->
          <view class="amount">
            <view class="price">
              <text v-if="currentSku.isActivity">
                ￥{{ currentSku.amount }}
              </text>
              <text :class="{ old: currentSku.isActivity }">
                ￥{{ currentSku.sale_price }}
              </text>
            </view>

            <u-text
              v-if="currentSku.barcode"
              :text="`商品条码：${currentSku.barcode}`"
              :lines="1"
            ></u-text>
            <u-text :text="`库存：${currentSku.stock}`" :lines="1"></u-text>
          </view>
          <!-- 商品数量选择 -->
          <view class="flex items-center">
            <up-number-box
              v-model="quantity"
              :min="min"
              :max="canSaleCount"
            ></up-number-box>
            <text class="ml-20">
              <u-text :text="`可售数量：${canSaleCount}`"></u-text>
            </text>
          </view>
        </view>
      </view>
      <!-- 间隔 -->
      <u-gap height="20"></u-gap>
      <!-- 滚动区域，用于显示规格列表 -->
      <scroll-view scroll-y style="height: 600rpx">
        <view class="skus">
          <!-- 遍历可迭代的规格数据 -->
          <view class="sku" v-for="(item, index) in iterableData" :key="index">
            <!-- 规格名称 -->
            <u-text :text="item.label" bold size="20"></u-text>
            <!-- 规格选项列表 -->
            <view class="sku-list">
              <!-- 遍历规格选项 -->
              <template v-for="(d, i) in item.data">
                <view
                  v-if="d"
                  :key="i"
                  :class="[
                    'sku-item',
                    selectData[item.label] == d ? 'active' : '',
                  ]"
                  @click="handleSelectSku(item.label, d)"
                >
                  <!-- 规格选项文本 -->
                  <text>{{ d }}</text>
                </view>
              </template>
            </view>
          </view>
        </view>
      </scroll-view>
      <view v-if="currentSku.id" class="flex gap-20 items-center">
        <view v-if="type == 'selection'" class="flex-1">
          <up-input
            placeholder="请输入该规格的云店价格"
            type="number"
            v-model="currentSku.amount"
          ></up-input>
        </view>
        <view class="flex-1">
          <!-- 确认按钮 -->
          <u-button type="primary" @click="handleConfirm"> 确认 </u-button>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { useStore } from "vuex";
import { goodsDetail, addStore } from "@/common/apis/goods.js";

// 获取 Vuex 存储实例
const store = useStore();

// 定义自定义事件，用于向父组件发送确认信息
const emits = defineEmits(["confirm"]);

// 定义组件接收的 props
const props = defineProps({
  // 商品 ID，类型可以是数字或字符串
  productId: [Number, String],
  // cart 加入购物车操作 store加入云店操作
  type: {
    type: String,
    default: "cart",
  },
  activitySkus: {
    type: Array,
    default: () => [],
  },
});

// 定义双向绑定的 show 模型
const show = defineModel("show");

const skus = ref([]);

const min = ref(1);

/**
 * 计算属性，用于获取购物车检查状态
 * @returns {boolean} 购物车检查状态
 */
const checkCart = computed(() => {
  return store.state.cart.checkCart;
});

const typeTitleMap = {
  cart: "加入购物车",
  selection: "加入云店",
};

const title = computed(() => {
  return typeTitleMap[props.type] || "选择规格";
});

// 商品数量，初始值为 1
const quantity = ref(1);

// 已选择的规格数据
const selectData = ref({});

/**
 * 处理 skus 数据为可迭代数据
 * @returns {Array} 处理后的可迭代数据
 */
const iterableData = computed(() => {
  // 用于存储已经处理过的 key
  const processedKeys = {};

  // 遍历数据数组
  skus.value.forEach((item) => {
    item.attributes.forEach((attr) => {
      const { key, value } = attr;
      if (!processedKeys[key]) {
        // 如果该 key 还未处理过，创建一个新的对象
        const newItem = {
          label: key,
          data: [value],
        };
        processedKeys[key] = newItem;
      } else {
        // 如果该 key 已经处理过，将 value 添加到对应的 data 数组中
        processedKeys[key].data = Array.from(
          new Set([...processedKeys[key].data, value])
        );
      }
    });
  });

  return Object.values(processedKeys);
});

/**
 * 计算当前选中的 SKU
 * @returns {Object} 当前选中的 SKU 信息
 */
const currentSku = computed(() => {
  const sku = skus.value.find((i) => {
    return Object.keys(selectData.value).every((key) => {
      return i.attributes.some((attr) => {
        return attr.key == key && attr.value == selectData.value[key];
      });
    });
  });
  return sku
    ? sku
    : {
        image_url: "",
        barcode: "",
        sale_price: 0,
        stock: "",
        isActivity: false,
      };
});

// 当前选中的 SKU 中得购物车
const currentCartSku = computed(() => {
  return store.state.cart.list.find((i) => {
    return i.variant.id == currentSku.value.id;
  });
});

const canSaleCount = computed(() => {
  if (currentCartSku.value) {
    return currentSku.value.stock - currentCartSku.value.quantity;
  }
  return currentSku.value.stock;
});

/**
 * 监听 show 变量的变化
 * 当 show 为 true 时，初始化选择数据
 */
watch(show, async (val) => {
  if (val) {
    await getGoodsDetail();
    if (props.activitySkus.length > 0) {
      selectData.value = props.activitySkus[0].variant.attributes.reduce(
        (acc, cur) => {
          acc[cur.key] = cur.value;
          return acc;
        },
        {}
      );
    } else {
      iterableData.value.forEach((item) => {
        selectData.value[item.label] = item.data[0];
      });
    }
  } else {
    selectData.value = {};
  }
});

async function getGoodsDetail() {
  const response = await goodsDetail(props.productId);
  if (response) {
    const activitySkuIds = props.activitySkus.map((sku) => sku.variant.id);
    skus.value = response.skus.map((i) => {
      if (activitySkuIds.includes(i.id)) {
        i.isActivity = true;
        const currentActivitySku = props.activitySkus.find(
          (sku) => sku.variant.id == i.id
        );
        i.amount = currentActivitySku.amount;
        i.activityVariantId = currentActivitySku.id;
      } else {
        i.amount = i.sale_price;
      }
      return i;
    });
    console.log(skus.value);
    min.value = response.min_sale_quantity;
  }
}

/**
 * 处理图片预览事件
 * @description 调用 uni.previewImage 方法预览当前商品图片
 */
function handlePreviewImage() {
  uni.previewImage({
    current: 0,
    count: 1,
    urls: [currentSku.value.image_url],
    showmenu: true,
  });
}

/**
 * 处理规格选择事件
 * @param {string} label 规格名称
 * @param {string} value 规格值
 * @description 根据选择的规格更新 selectData
 */
function handleSelectSku(label, value) {
  if (selectData.value[label] == value) {
    delete selectData.value[label];
  } else {
    selectData.value[label] = value;
  }
}

/**
 * 处理确认事件
 * @description 向购物车添加商品，更新购物车列表，并关闭弹出框
 */
async function handleConfirm() {
  if (props.type == "cart") {
    await addCart();
  } else if (props.type == "selection") {
    await selectionToStore();
  }
}

async function addCart() {
  if (canSaleCount.value <= 0) {
    return uni.showToast({
      title: "可售数量不足",
      icon: "error",
    });
  }
  if (Object.keys(selectData.value).length < iterableData.value.length) {
    return uni.showToast({
      title: "请选择完整规格",
      icon: "error",
    });
  }
  await store.dispatch("fetchAddCart", {
    product_id: props.productId,
    quantity: quantity.value,
    variant_id: currentSku.value.id,
    promotional_variant_id: currentSku.value.activityVariantId,
  });
  await store.dispatch("fetchCartList");
  show.value = false;
  uni.showToast({
    title: "已加入购物车",
    icon: "success",
  });
}

async function selectionToStore() {
  const response = await addStore({
    product_id: props.productId,
    lines: skus.value.map((i) => {
      return {
        variant_id: i.id,
        amount: i.amount,
      };
    }),
  });
  if (response) {
    uni.showToast({
      title: "已加入云店",
      icon: "success",
    });
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding-bottom: env(safe-area-inset-bottom + 20rpx);
  .info {
    .price {
      font-size: 38rpx;
      color: #ff2522;

      .old {
        text-decoration: line-through;
        color: #ccc;
        margin-left: 10rpx;
      }
    }
  }
  .skus {
    overflow: hidden;
    .sku {
      margin-top: 20rpx;
      .sku-list {
        margin-top: 20rpx;
        display: flex;
        flex-wrap: wrap;

        .sku-item {
          background-color: #f6f6f6;
          padding: 10rpx 20rpx;
          margin-right: 20rpx;
          border-radius: 10rpx;
          box-sizing: border-box;
          border: 2px solid $u-info-light;
          margin-bottom: 20rpx;

          &.active {
            background-color: $u-primary-light;
            color: #fff;
            border: 2px solid $u-primary;
          }
        }
      }
    }
  }
}
</style>
